package code._13io.other._04serialize;

import java.io.*;

public class Demo {
    public static void main(String[] args) throws IOException, ClassNotFoundException {
        serialize();
        unSerialize();
    }

    private static void unSerialize() throws IOException, ClassNotFoundException {
        ObjectInputStream in =
                new ObjectInputStream(new FileInputStream("fileTest\\a.txt"));
        Object o = in.readObject();
        System.out.println("o = " + o);
        in.close();

    }

    private static void serialize() throws IOException {
        // ObjectOutputStream(OutputStream out)
        // 创建写入指定 OutputStream 的 ObjectOutputStream。
        // 创建序列化流对象
        ObjectOutputStream out =
                new ObjectOutputStream(new FileOutputStream("fileTest\\a.txt"));

        // 创建要被序列化的对象
        // Student student = new Student("zs", 20);
        Student student = new Student("zs", 20, 99);

        // writeObject(Object obj)

        out.writeObject(student);

        // close
        out.close();
    }
}

class Student implements Serializable {
    String name;
    int age;
    // 某个成员变量不想被序列化  可以使用关键字transient修饰它
    transient int score;

    static final long serialVersionUID = -7495866893823577022L;

    public Student(String name, int age, int score) {
        this.name = name;
        this.age = age;
        this.score = score;
    }

    public Student(String name, int age) {
        this.name = name;
        this.age = age;
    }

    @Override
    public String toString() {
        return "Student{" +
                "name='" + name + '\'' +
                ", age=" + age +
                ", score=" + score +
                '}';
    }
}
